import './index.scss'
import userStore from '@/store'
import {
  UserOutlined,
  UserAddOutlined,
  LogoutOutlined,
} from '@ant-design/icons'
import { HappyProvider } from '@ant-design/happy-work-theme'
import { Button, Form, Input } from 'antd'
import { useShowPromiseModal, useOpenMessageThrottle } from '@/hook'
import { useEffect, useState } from 'react'
import { observer } from 'mobx-react'
import { userLogin, userRegister } from '@/request'

const Profile = ({handleRefresh}) => {
  const showPromiseModal = useShowPromiseModal('confirm')
  const openMessage = useOpenMessageThrottle(1000)

  const [userLoginForm, setUserLoginForm] = useState({
    username: '',
    password: '',
  })

  const [userRegisterForm, setUserRegisterForm] = useState({
    username: '',
    password: '',
    confirmPassword: '',
  })

  const loginFormHandle = (target, value) => {
    setUserLoginForm((state) => {
      state[target] = value
      return { ...state }
    })
  }

  const registerFormHandle = (target, value) => {
    setUserRegisterForm((state) => {
      state[target] = value
      return { ...state }
    })
  }

  const userLoginHandle = () => {
    showPromiseModal({
      title: '登录',
      icon: <UserOutlined />,
      content: promiseConfirmLoginContentDom(),
      onOk(close) {
        setUserLoginForm((state) => {
          if (state.username === '' || state.password === '') {
            openMessage({ type: 'warning', content: '用户名和密码不能为空' })
            return state
          }
          userLoginInit(state, close)
          return state
        })
      },
    })
  }

  const userRegisterHandle = async () => {
    showPromiseModal({
      title: '注册',
      icon: <UserAddOutlined />,
      content: promiseConfirmRegisterContentDom(),
      onOk(close) {
        setUserRegisterForm((state) => {
          if (
            state.username === '' ||
            state.password === '' ||
            state.confirmPassword === ''
          ) {
            openMessage({ type: 'warning', content: '请填写完整的注册信息' })
            return state
          } else if (state.password !== state.confirmPassword) {
            openMessage({ type: 'warning', content: '两次密码输入不一致' })
            return state
          }
          userRegisterInit(state, close)
          return state
        })
      },
      onCancel() {
        setUserRegisterForm({ username: '', password: '', confirmPassword: '' })
      },
    })
  }

  const userLoginInit = async (data, close) => {
    try {
      const res = await userLogin(data)
      if (res.code === 10400) {
        openMessage({ type: 'error', content: res.data })
        return
      }
      if (res.code === 0) {
        userStore.login(res.data)
        setUserLoginForm({ username: '', password: '' })
        openMessage({ type: 'success', content: '登录成功' })
        window.location.reload()
      }
    } catch (error) {
      openMessage({ type: 'error', content: error.message })
    }
  }

  const userRegisterInit = async (data, close) => {
    try {
      const res = await userRegister(data)
      if (res.code === 10400) {
        openMessage({ type: 'error', content: res.data })
        return
      }
      if (res.code === 0) {
        userStore.login(res.data)
        setUserRegisterForm({ username: '', password: '', confirmPassword: '' })
        openMessage({ type: 'success', content: '注册成功' })
        close()
      }
    } catch (error) {
      openMessage({ type: 'error', content: error.message })
    }
  }

  const logout = () => {
    showPromiseModal({
      title: '退出登录',
      icon: <LogoutOutlined />,
      content: '确认退出',
      onOk() {
        userStore.logout()
        openMessage({ type: 'success', content: '已退出登录' })
        window.location.reload()
      },
    })
  }

  const promiseConfirmLoginContentDom = () => {
    return (
      <div className="login">
        <Form name="basic" autoComplete="off">
          <Form.Item
            label="账户"
            name="username"
            rules={[{ required: true, message: '请输入账户！' }]}
            initialValue={userLoginForm.username}
          >
            <Input
              placeholder="输入账户"
              onChange={(e) => {
                loginFormHandle('username', e.target.value)
              }}
            />
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: '请输入密码！' }]}
            initialValue={userLoginForm.password}
          >
            <Input.Password
              placeholder="输入密码"
              onChange={(e) => {
                loginFormHandle('password', e.target.value)
              }}
            />
          </Form.Item>
        </Form>
      </div>
    )
  }

  const promiseConfirmRegisterContentDom = () => {
    return (
      <div className="register">
        <Form name="basic" autoComplete="off">
          <Form.Item
            label="账户"
            name="username"
            rules={[{ required: true, message: '请输入账户！' }]}
            initialValue={userRegisterForm.username}
          >
            <Input
              placeholder="输入账户"
              onChange={(e) => {
                registerFormHandle('username', e.target.value)
              }}
            />
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: '请输入密码！' }]}
            initialValue={userRegisterForm.password}
          >
            <Input.Password
              placeholder="输入密码"
              onChange={(e) => {
                registerFormHandle('password', e.target.value)
              }}
            />
          </Form.Item>
          <Form.Item
            label="确认密码"
            name="confirmPassword"
            rules={[{ required: true, message: '请确认密码！' }]}
            initialValue={userRegisterForm.confirmPassword}
          >
            <Input.Password
              placeholder="确认密码"
              onChange={(e) => {
                registerFormHandle('confirmPassword', e.target.value)
              }}
            />
          </Form.Item>
        </Form>
      </div>
    )
  }

  useEffect(() => {
    const user = JSON.parse(localStorage.getItem('user'))
    if (user) {
      userStore.login(user)
    }
  }, [])

  return (
    <>
      {userStore.isLogin ? (
        <div className="profile">
          <div className="imgBox">
            <img
              src="https://dullwolf.oss-cn-shenzhen.aliyuncs.com/1143644962798174208.png"
              alt=""
            />
          </div>
          <div className="content">
            <div className="details">
              <div className="name">{userStore.user.userName}</div>
              <div className="desc">
                特别感谢 蠢狼dullwolf 小埋 纯度 为本站搭建设计 UI 样式
              </div>
              <HappyProvider>
                <Button
                  type="primary"
                  icon={<LogoutOutlined />}
                  onClick={logout}
                >
                  退出登录
                </Button>
              </HappyProvider>
            </div>
          </div>
        </div>
      ) : (
        <div className="profile">
          <div className="imgBox">
            <img
              src="https://dullwolf.oss-cn-shenzhen.aliyuncs.com/1143644962798174208.png"
              alt=""
            />
          </div>
          <div className="content">
            <div className="details">
              <div className="name">椰羊动漫</div>
              <div className="desc">
                  新网站：mio.natapp1.cc
              </div>
              <HappyProvider>
                <Button
                  type="primary"
                  icon={<UserOutlined />}
                  style={{ background: '#ff5f95', gap: '1px' }}
                  onClick={userLoginHandle}
                >
                  登录
                </Button>
                <Button
                  type="primary"
                  icon={<UserAddOutlined />}
                  style={{
                    background: '#4ac959',
                    gap: '1px',
                    marginLeft: '10px',
                  }}
                  onClick={userRegisterHandle}
                >
                  注册
                </Button>
              </HappyProvider>
            </div>
          </div>
        </div>
      )}
    </>
  )
}

export default observer(Profile)
